/*
* 1videoConference -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, Adiance Technologies Pvt. Ltd.
*
* Hardik Sanghvi <hardik.sanghvi @adiance.com>
*
* See http://www.1videoconference.org for more information about
* the 1videoConference project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Reflection;
using System.IO;
using _videoConference.BAL;
using System.Windows.Navigation;
using System.Windows;


namespace ZipInfo
{
    public class CliSvcZipInfo
    {
        Assembly b = Assembly.GetAssembly(typeof(CliSvcZipInfo));
        string zipFolder;
        string[] strFilesClient;
        string[] strFilesServer;
        string[] strOrgFileList;
        string[] strSerFileList;

        List<string> RequiredFiles = new List<string>();
        FileStream stream;
        string Channel = "";

        public NetPeerService.NetPeerClient npcZipInfoMain = null;
        public NetPeerService.NetPeerClient npcZipInfoSub = null;
        object objZipInfoMain = new CsvcZipInfoMain();
        object objZipInfoSub = new CsvcZipInfoSub();
        
        IsvcZipInfoMain ZipInfoMain;
        IsvcZipInfoSub ZipInfoSub;
        string MyMID = "";

        public delegate void DelZipDownloaded();
        public event DelZipDownloaded EntZipDownloaded;

        public CliSvcZipInfo()
        {
            MyMID = UserInfo.MeetingID;
            try
            {
                ((CsvcZipInfoMain)objZipInfoMain).entsvcJoin += new CsvcZipInfoMain.delsvcJoin(CliSvcZipInfo_entsvcJoin);
                ((CsvcZipInfoMain)objZipInfoMain).entsvcStarted += new CsvcZipInfoMain.delsvcServiceStarted(CliSvcZipInfo_entsvcStarted);
                ((CsvcZipInfoMain)objZipInfoMain).entsvcUnJoin += new CsvcZipInfoMain.delsvcUnJoin(CliSvcZipInfo_entsvcUnJoin);

                //npcZipInfoMain = new NetPeerService.NetPeerClient();
                //ZipInfoMain = (IsvcZipInfoMain)npcZipInfoMain.OpenClient<IsvcZipInfoMain>("net.tcp://"+UserInfo.CreMachName+":2500/ZipInfo","ZipInfoMeshM"+UserInfo.MeetingID ,ref objZipInfoMain);
                ////MessageBox.Show("Main zip channel");
                //ZipInfoMain.svcJoin(Environment.MachineName);

                npcZipInfoMain = new NetPeerService.NetPeerClient();
                ZipInfoMain = (IsvcZipInfoMain)npcZipInfoMain.OpenClient<IsvcZipInfoMain>("net.tcp://" + UserInfo.CreMachName + ":2500/ZipInfo", "ZipInfoMesh", ref objZipInfoMain);
                ZipInfoMain.svcJoin(UserInfo.UserName, MyMID);

            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo()--:--" + exp.Message);
            }  
        }

        void CliSvcZipInfo_entsvcJoin(string uName,string MeetingID)
        {

        }

        

        void CliSvcZipInfo_entsvcStarted(string uName, string URI)
        {
            try
            {
                if (uName.ToLower() == UserInfo.UserName.ToLower())
                {
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcJoin += new CsvcZipInfoSub.DelsvcJoin(CliSvcZipInfo_EntsvcJoin);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcZipFileInfo += new CsvcZipInfoSub.DelsvcZipFileInfo(CliSvcZipInfo_EntsvcZipFileInfo);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcSetZipName += new CsvcZipInfoSub.DelsvcSetZipName(CliSvcZipInfo_EntsvcSetZipName);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcSendZipFile += new CsvcZipInfoSub.DelsvcSendZipFile(CliSvcZipInfo_EntsvcSendZipFile);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcSaveZipFile += new CsvcZipInfoSub.DelsvcSaveZipFile(CliSvcZipInfo_EntsvcSaveZipFile);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcUnjoin += new CsvcZipInfoSub.DelsvcUnjoin(CliSvcZipInfo_EntsvcUnjoin);
                    ((CsvcZipInfoSub)objZipInfoSub).EntsvcServerFileList+=new CsvcZipInfoSub.DelsvcServerFileList(CliSvcZipInfo_EntsvcServerFileList);

                    npcZipInfoSub = new NetPeerService.NetPeerClient();
                    ////ZipInfoSub = (IsvcZipInfoSub)npcZipInfoSub.OpenClient<IsvcZipInfoSub>(URI, ref objZipInfoSub);
                    //Channel = URI;
                    ////ZipInfoSub.svcJoin();
                    //System.Threading.Thread.Sleep(1000);
                    ////MessageBox.Show("Sub channel");
                    //t1_Tick();

                    ZipInfoSub = (IsvcZipInfoSub)npcZipInfoSub.OpenClient<IsvcZipInfoSub>(URI, "ZipInfoSubMeshM" + MyMID + "U" + uName, ref objZipInfoSub);
                    Channel = URI;
                    ZipInfoSub.svcJoin();
                    System.Threading.Thread.Sleep(1000);
                    t1_Tick();


                }
            }
            catch (Exception exp)
            {
                //MessageBox.Show(exp.Message);
            }
        }

        void CliSvcZipInfo_entsvcUnJoin(string uName)
        {
            if (UserInfo.UserName.ToLower() == uName.ToLower())
            {
                //MessageBox.Show("Unjoined called");
                string balfolder = b.Location.Replace("1videoConference.BAL.dll", @"Business Layer");
                string controlfolder = b.Location.Replace("1videoConference.BAL.dll", @"Presentation Layer");
                string datafolder = b.Location.Replace("1videoConference.BAL.dll", @"Data Layer");

                for (int i = 0; i < strFilesClient.Length; i++)
                {
                    if (strSerFileList.Length.ToString() == i.ToString())
                    {
                        for (int k = i; k < strFilesClient.Length; k++)
                        {
                            FileInfo fi = new FileInfo(zipFolder + @"\" + strFilesClient[k].Split(':')[0]);
                            DirectoryInfo DirBAL = new DirectoryInfo(balfolder + @"\" + strFilesClient[k].Split('.')[0]);
                            DirectoryInfo DirDAL = new DirectoryInfo(datafolder + @"\" + strFilesClient[k].Split('.')[0]);
                            DirectoryInfo DirControl = new DirectoryInfo(controlfolder + @"\" + strFilesClient[k].Split('.')[0]);
                            fi.Delete();
                            DirBAL.Delete(true);
                            DirDAL.Delete(true);
                            DirControl.Delete(true);
                        }
                        break;
                    }
                    if (strFilesClient[i] != strSerFileList[i])
                    {
                        FileInfo fi = new FileInfo(zipFolder + @"\" + strFilesClient[i].Split(':')[0]);
                        DirectoryInfo DirBAL = new DirectoryInfo(balfolder + @"\" + strFilesClient[i].Split('.')[0]);
                        DirectoryInfo DirDAL = new DirectoryInfo(datafolder + @"\" + strFilesClient[i].Split('.')[0]);
                        DirectoryInfo DirControl = new DirectoryInfo(controlfolder + @"\" + strFilesClient[i].Split('.')[0]);
                        fi.Delete();
                        DirBAL.Delete(true);
                        DirDAL.Delete(true);
                        DirControl.Delete(true);

                        strOrgFileList = Directory.GetFiles(zipFolder);
                        strFilesClient = new string[strOrgFileList.Length];
                        for (int j = 0; j < strOrgFileList.Length; j++)
                        {
                            string[] strFname = strOrgFileList[j].Split('\\');
                            stream = new FileStream(strOrgFileList[j], FileMode.Open, FileAccess.Read);
                            strFilesClient[j] = strFname[strFname.Length - 1].ToString() + ":" + stream.Length.ToString();
                            stream.Close();
                        }
                        i--;
                    }
                }
                EntZipDownloaded();
            }            
        }
        void CliSvcZipInfo_EntsvcJoin()
        {
            
        }

        void CliSvcZipInfo_EntsvcZipFileInfo(string[] fileList)
        {

        }

        void CliSvcZipInfo_EntsvcSetZipName(string zipfileName)
        {
            try
            {
                stream = File.Open(zipFolder + "\\" + zipfileName.Split(':')[0], FileMode.Create, FileAccess.ReadWrite);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcSetZipName()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo_EntsvcSetZipName()--:--" + exp.Message);
            }
        }

        void CliSvcZipInfo_EntsvcSendZipFile(byte[] zipfile)
        {
            try
            {
                stream.Write(zipfile, 0, zipfile.Length);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcSendZipFile()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo_EntsvcSendZipFile()--:--" + exp.Message);
            }
        }

        void CliSvcZipInfo_EntsvcSaveZipFile()
        {
            try
            {
                stream.Close();
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcSaveZipFile()--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo_EntsvcSaveZipFile()--:--" + exp.Message);
            }
        }

        void CliSvcZipInfo_EntsvcUnjoin()
        {
            try
            {
                strOrgFileList = Directory.GetFiles(zipFolder);
                strFilesClient = new string[strOrgFileList.Length];
                for (int j = 0; j < strOrgFileList.Length; j++)
                {
                    string[] strFname = strOrgFileList[j].Split('\\');
                    stream = new FileStream(strOrgFileList[j], FileMode.Open, FileAccess.Read);
                    strFilesClient[j] = strFname[strFname.Length - 1].ToString() + ":" + stream.Length.ToString();
                    stream.Close();
                }

                //MessageBox.Show("EntZipDownloaded 2 b called");                   



                #region To Extract Files
                
                    string tempfolder = b.Location.Replace("1videoConference.BAL.dll", @"Temp");
                    string balfolder = b.Location.Replace("1videoConference.BAL.dll", @"Business Layer");
                    string controlfolder = b.Location.Replace("1videoConference.BAL.dll", @"Presentation Layer");
                    string datafolder = b.Location.Replace("1videoConference.BAL.dll", @"Data Layer");
                    string imagefolder = b.Location.Replace("1videoConference.BAL.dll", @"Image");
                    string sqlfolder = b.Location.Replace("1videoConference.BAL.dll", @"SQL Scripts");
                    string modulename = "";
                    strOrgFileList = Directory.GetFiles(zipFolder);
                    if (UserInfo.zipextract == true)
                    {
                        _videoConference.ZipUnzip.Zip.FastZip fz = new _videoConference.ZipUnzip.Zip.FastZip();
                        for (int i = 0; i < strOrgFileList.Length; i++)
                        {

                            fz.ExtractZip(strOrgFileList[i].ToString(), tempfolder, null);
                            modulename = strOrgFileList[i].Split('\\')[strOrgFileList[i].Split('\\').Length - 1].ToString().Replace(".zip", "");
                            if (Directory.Exists(controlfolder + "\\" + modulename))
                            {
                                Directory.Delete(controlfolder + "\\" + modulename, true);
                            }
                            Directory.CreateDirectory(controlfolder + "\\" + modulename);

                            if (Directory.Exists(balfolder + "\\" + modulename))
                            {
                                Directory.Delete(balfolder + "\\" + modulename, true);
                            }
                            Directory.CreateDirectory(balfolder + "\\" + modulename);

                            if (Directory.Exists(datafolder + "\\" + modulename))
                            {
                                Directory.Delete(datafolder + "\\" + modulename, true);
                            }
                            Directory.CreateDirectory(datafolder + "\\" + modulename);

                            string[] dirnameorg = Directory.GetDirectories(tempfolder);
                            string[] dirname = Directory.GetDirectories(dirnameorg[0]);

                            for (int k = 0; k < dirname.Length; k++)
                            {
                                string[] strSplit = dirname[k].ToString().Split('\\');

                                if (strSplit[strSplit.Length - 1].ToUpper() == "BAL")
                                {
                                    string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                                    for (int j = 0; j < balfilenames.Length; j++)
                                    {
                                        string[] filefoldername = balfilenames[j].Split('\\');
                                        File.Copy(balfilenames[j], balfolder + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                                    }
                                }

                                if (strSplit[strSplit.Length - 1].ToUpper() == "DAL")
                                {
                                    string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                                    for (int j = 0; j < balfilenames.Length; j++)
                                    {
                                        string[] filefoldername = balfilenames[j].Split('\\');
                                        File.Copy(balfilenames[j], datafolder + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                                    }
                                }

                                if (strSplit[strSplit.Length - 1].ToUpper() == "CONTROL")
                                {
                                    string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                                    for (int j = 0; j < balfilenames.Length; j++)
                                    {
                                        string[] filefoldername = balfilenames[j].Split('\\');
                                        File.Copy(balfilenames[j], controlfolder + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                                    }
                                }

                                if (strSplit[strSplit.Length - 1].ToUpper() == "IMAGES")
                                {
                                    string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                                    for (int j = 0; j < balfilenames.Length; j++)
                                    {
                                        string[] filefoldername = balfilenames[j].Split('\\');
                                        File.Copy(balfilenames[j], imagefolder + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                                    }
                                }

                                if (strSplit[strSplit.Length - 1].ToUpper() == "SQL")
                                {
                                    string[] baldirnames = Directory.GetDirectories(dirname[k].ToString());
                                    for (int dircount = 0; dircount < baldirnames.Length; dircount++)
                                    {
                                        string[] files = baldirnames[dircount].Split('\\');
                                        Directory.CreateDirectory(sqlfolder + "\\" + modulename + "\\" + files[files.Length - 1].ToString());
                                        string[] sqlfilenames = Directory.GetFiles(baldirnames[dircount]);
                                        for (int j = 0; j < sqlfilenames.Length; j++)
                                        {
                                            string[] filefoldername = sqlfilenames[j].Split('\\');
                                            File.Copy(sqlfilenames[j], sqlfolder + "\\" + modulename + "\\" + files[files.Length - 1].ToString() + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                                        }
                                    }
                                }
                            }
                            try
                            {
                                //Directory.Delete(dirnameorg[0], true);
                                DirectoryInfo di = new DirectoryInfo(dirnameorg[0].ToString());
                                di.Delete(true);
                            }


                            catch (Exception exp)
                            {
                                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcUnjoin()1--:--");
                                clsUtility.LogException = exp;
                                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo_EntsvcUnjoin1()--:--" + exp.Message);
                            }
                        }
                    }
                #endregion

                ZipInfoMain.svcUnJoin(UserInfo.UserName);
                System.Threading.Thread.Sleep(1000);

                
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcUnjoin()2--:--");
                clsUtility.LogException = exp;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--CliSvcZipInfo_EntsvcUnjoin2()--:--" + exp.Message);
            }  
        }

        void CliSvcZipInfo_EntsvcServerFileList(string[] strServerFileInfo)
        {
            strSerFileList = new string[strServerFileInfo.Length];
            for (int i = 0; i < strServerFileInfo.Length; i++)
            {
                strSerFileList[i] = strServerFileInfo[i];
            }
        }


        void t1_Tick()
        {
            try
            {
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Zip Files"))
                {
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory+ "Zip Files");
                }

                zipFolder = AppDomain.CurrentDomain.BaseDirectory + "Zip Files";
                strOrgFileList = Directory.GetFiles(zipFolder);
                if (strOrgFileList.Length != 0)
                {
                    strFilesClient = new string[strOrgFileList.Length];

                    for (int i = 0; i < strOrgFileList.Length; i++)
                    {
                        string[] strFname = strOrgFileList[i].Split('\\');
                        stream = new FileStream(strOrgFileList[i], FileMode.Open, FileAccess.Read);
                        strFilesClient[i] = strFname[strFname.Length - 1].ToString() + ":" + stream.Length.ToString();
                        stream.Close();
                    }
                    ZipInfoSub.svcZipFileInfo(strFilesClient);
                }
                else
                {
                    strFilesClient = new string[1];
                    strFilesClient[0] = "None";
                    ZipInfoSub.svcZipFileInfo(strFilesClient);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "1videoConference--:--svcZipInfo.cs--:--ClisvcZipInfo_EntsvcUnjoin()3--:--");
                clsUtility.LogException = ex;
                //MessageBox.Show("1videoConference--:--svcZipInfo.cs--:--t1_Tick()--:--" + ex.Message);
            }
        }

    }

}
